﻿using Abp;
using Abp.Domain.Repositories;
using Abp.UI;
using Camc.Duct.AppUserInfos.Dto;
using Camc.Duct.Authorization.Users;
using Camc.Duct.Authorization.Users.Dto;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;
using System.Threading.Tasks;

namespace Camc.Duct.AppUserInfos
{
 public   class AppUserInfoAppService: DuctAppServiceBase
    {
        private readonly IRepository<AppUserInfo, long> _appUserInfoRepository;
        private readonly UserManager _userManager;
        public AppUserInfoAppService(IRepository<AppUserInfo, long> appUserInfoRepository, UserManager userManager)
        {
            _appUserInfoRepository = appUserInfoRepository;
            _userManager = userManager;
        }

        /// <summary>
        /// 获取微信用户信息存入数据库
        /// </summary>
        /// <param name="userInfo">传入的微信用户信息</param>
        /// <returns></returns>
        public   AppUserInfo GetUserInfo(string userInfo)
        {


            #region 反序列化传入的微信用户信息




            JObject jObject = JObject.Parse(userInfo);

            JSchema accessSchema = JSchema.Parse(JsonConvert.SerializeObject(


                 new
                 {
                     avatarUrl = "",
                     city = "",
                     country = "",
                     language = "zh_CN",
                     gender = 0,
                     nickName = "",
                     openid = "",
                     province = "",
                 }

            ));
            if (!jObject.IsValid(accessSchema))
            {
                throw new UserFriendlyException("accessCode Json inVaild");
            }
            //AppUserInfo userInfo = JsonConvert.DeserializeObject<AppUserInfo>(jObject["userInfo"].ToString());
            string avatarUrl = jObject["avatarUrl"].ToString();
            string city = jObject["city"].ToString();
            string country = jObject["country"].ToString();
            string language = jObject["language"].ToString();
            int gender = jObject["gender"].GetHashCode();
            string nickName = jObject["nickName"].ToString();
            string openid = jObject["openid"].ToString();
            string province = jObject["province"].ToString();

            #endregion
            //var userinfolist = new AppUserInfo()
            //{
            //    AvatarUrl = avatarUrl,
            //    City = city,
            //    Country = country,
            //    Language = language,
            //    Gender = gender,
            //    NickName = nickName,
            //    Openid = openid,
            //    Province = province,
            //};

            // 查询数据库内userinfo表中openid等于传入的openid相等的数据

            var query =  _appUserInfoRepository.FirstOrDefault(p => p.Openid == openid&&p.IsDeleted==false);
            if (query != null)
            {
                query.AvatarUrl = avatarUrl;
                query.City = city;
                query.Country = country;
                query.Language = language;
                query.Gender = gender;
                query.NickName = nickName;
                query.Province = province;
                _appUserInfoRepository.Update(query);
                return query;
            }
            else
            {
                var users = new AppUserInfo()
                {
                    Openid = openid
                };
                _appUserInfoRepository.Insert(users);
                return users;
            }
            //赋值给查询到的数据
            //query.AvatarUrl = avatarUrl;
            //query.City = city;
            //query.Country = country;
            //query.Language = language;
            //query.Gender = gender;
            //query.NickName = nickName;
            //query.Province = province;
            //更新数据库信息
          
            //执行更新数据库信息
         //   await _appUserInfoRepository.GetDbContext().SaveChangesAsync();
            //返回对象
       

        }

        public   WeChatUserInfo GetWeChatUserInfo(getWeChatUserInfoinput input)
        {

            var user =  _userManager.FindByIdAsync(input.UserId).Result;

            var appuser =  _appUserInfoRepository.FirstOrDefaultAsync(p => p.Openid == input.openId && p.IsDeleted == false).Result;

            var weChatUserInfo = new WeChatUserInfo();

            var appUserInfo = new AppUserInfoListDto();
            var userinfo = new UserListDto();
            userinfo = ObjectMapper.Map<UserListDto>(user);
            appUserInfo = ObjectMapper.Map<AppUserInfoListDto>(appuser);
            
            weChatUserInfo.AppUserInfo = appUserInfo;
            weChatUserInfo.user = userinfo;
            return weChatUserInfo;

        }

        public async Task<AppUserInfo> GetOpenId(string openid)
        {
            

            var query = await _appUserInfoRepository.FirstOrDefaultAsync(p=>p.Openid==openid&&p.IsDeleted==false);
            if(query == null)
            {
                var userinfo = new AppUserInfo()
                {
                    Openid = openid,

                };
                await _appUserInfoRepository.InsertAsync(userinfo);
                return userinfo;
            }
            else
            {
                return query;
            }


          
            }
        }
    }

